// 导入 express 模块
const express = require("express");
const fs = require("fs");
const path = require("path");

var data = fs.readFileSync(path.resolve(__dirname, "public/404.html"));
// console.log(data.toString(), __dirname);

// 创建 web 对象
const app = express();

// 声明防盗链中间件
function secureChain(req, res, next) {
  // 检测请求头中的 referer
  // 获取 referer 的值
  var referer = req.get("referer");
  console.log(referer);

  if (referer) {
    // 获取 url
    var url = new URL(referer);
    // 获取 hostname
    var hostname = url.hostname;
    console.log(hostname);

    // 判断
    if (hostname == "172.20.110.53") {
      res.send(data);
      return;
    }
  }

  // 继续执行
  next();
}
app.use(secureChain);

// 设置静态资源中间件
app.use(express.static(__dirname + "/" + "public/"));
console.log(__dirname);

// 监听端口，启动服务
app.listen(8000, () => {
  console.log("图片防盗链：服务已经启动……");
});
